package org.example.spring_annotation.config;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;
import java.util.EnumSet;

public class WebInit implements WebApplicationInitializer {
    private Logger logger = LogManager.getLogger(WebInit.class);
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        logger.info("-------->1.开始启动web应用");
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();

        // spring-mvc 上下文
        context.register(WebMvcConfig.class);
        context.setServletContext(servletContext);

        /*
         * 创建并注册  DispatcherServlet
         */
        DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
        ServletRegistration.Dynamic dynamic = servletContext.addServlet("dispatcherServlet", dispatcherServlet);
        dynamic.setLoadOnStartup(1);
        dynamic.addMapping("/");

        servletContext.addListener(new ContextLoaderListener(context));

        /*
         * CharacterEncodingFilter: 解决中文乱码问题
         */
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("utf-8");
        FilterRegistration encodingFilter = servletContext.addFilter("characterEncodingFilter", characterEncodingFilter);
        encodingFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
        logger.info("-------->2.web应用启动完成.");
    }
}
